package com.apes.fn.pi.fnCommunal;

import com.alibaba.fastjson.JSONObject;
import com.apes.fn.server.servicePlan.service.ConditionBuilder;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.pi.service.PiManager;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.service.PartyRoleService;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.repository.BrandRepository;
import com.apes.scm.masterdata.product.repository.ProductRepository;
import com.apes.scm.masterdata.product.service.CategorySupplyRangeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * Creator: zouyc
 * CreateDate: 2020-03-09 16:25
 * Description:
 **/
@Service("fnCommunalService")
public class FnCommunalService extends DomainService {

    @Autowired
    PartyRoleService partyRoleService;
    @Autowired
    PiManager piManager;

    public static final String CONST_FNCOMMUNALSERVICE_PLATFORM_1001 = "1001";
    public static final String CONST_FNCOMMUNALSERVICE_PLATFORM_1007 = "1007";


    /**
     * 提供给系统外使用
     * dsFlag systemFlag deptId productId
     * @param simpleRequest
     * @return
     */
    public PartyRole getPlatformById(SimpleRequest simpleRequest){
        JSONObject jo = simpleRequest.getJO();
        return getPlatform(jo.getBoolean("dsFlag"),jo.getBoolean("systemFlag"),jo.getString("deptId"),jo.getString("productId"));
    }

    public PartyRole getPlatform(boolean a,boolean b, String deptId, String productId){
        Dept dept ;
        Product product;
        try {
            dept = SpringManager.getBean(DeptRepository.class).findOne(deptId);
        }catch (Exception e){
            throw new RuntimeException("门店编码在系统不存在，门店编码：" + deptId);
        }
        try {
            product = SpringManager.getBean(ProductRepository.class).findOne(productId);
        }catch (Exception e){
            throw new RuntimeException("商品编码在系统不存在：" + productId);
        }
        return getPlatform(a,b,dept,product);
    }

    /**
     * @param a 是否定损
     * @param dept 做单部门
     * @param product 商品
     * @return
     */
    public PartyRole getPlatform(boolean a,boolean b, Dept dept, Product product){
        boolean c ;
        boolean d = true;
        try {
            c = dept.getCompany().getParty().getCorporate().isWantInvoice();
        }catch (Exception e){
            throw new RuntimeException("查找门店对应公司是否开票失败，请检查是否配置");
        }
        if(product.getClassify() == null || product.getClassify().getId() == null)
            throw new RuntimeException("商品主数据定义不完整（品类），商品：" + product.getName());
        try {
             d = SpringManager.getBean(CategorySupplyRangeService.class).checkInRange(product.getClassify(), product.getBrand());
        }catch (Exception e){
            throw new RuntimeException("innerMistake:查找品类直供范围有误，请检查");
        }
        return getPlatform(a,b,c,d);
    }



    /**
     *
     * @param a  是否定损 true 是
     * @param b  新旧系统 true 新
     * @param c  是否开票 true 开
     *  d  直供范围 true 直供内 (2020-06-17 zdz要求去除品类直供,18:要求取价格需直供，不取价格不要求直供)
     * @return
     */
    public PartyRole getPlatform(boolean a,boolean b,boolean c,boolean d){
        String id = CONST_FNCOMMUNALSERVICE_PLATFORM_1001;
        if(!a && b && !c &&!d ) id = CONST_FNCOMMUNALSERVICE_PLATFORM_1007;
        PartyRole partyRole;
        try {
            partyRole = partyRoleService.findOne(id,"Company");
            if(partyRole == null) throw new Exception("");
        }catch (Exception e){
            throw new RuntimeException("未找到对应的平台，平台编码：" + id);
        }
        return partyRole;
    }

    /**
     * 去除直供范围判断平台
     * @param a
     * @param b
     * @param dept
     * @return
     */
    public PartyRole getPlatform(boolean a,boolean b, Dept dept){
        boolean c ;
        try {
            c = dept.getCompany().getParty().getCorporate().isWantInvoice();
        }catch (Exception e){
            throw new RuntimeException("查找门店对应公司是否开票失败，请检查是否配置");
        }
        return getPlatform(a,b,c);
    }

    private PartyRole getPlatform(boolean a,boolean b,boolean c){
        String id = CONST_FNCOMMUNALSERVICE_PLATFORM_1001;
        if(!a && b && !c ) id = CONST_FNCOMMUNALSERVICE_PLATFORM_1007;
        PartyRole partyRole;
        try {
            partyRole = partyRoleService.findOne(id,"Company");
            if(partyRole == null) throw new Exception("");
        }catch (Exception e){
            throw new RuntimeException("未找到对应的平台，平台编码：" + id);
        }
        return partyRole;
    }


    public Map getStock(Map map){
        JSONObject resultJson = piManager.synErp(
                "ipmServicePlanService.getKYSToOut", map
        );

        JSONObject reJson ;
        try {
            reJson = JSONObject.parseObject(resultJson.getString("obj"));
            if(reJson == null) throw new RuntimeException("");
        }catch (Exception e){
            return null;
        }

        return MapUtil.mapper("subStock",reJson.getJSONArray("subStock"),"generalStock",reJson.getJSONArray("generalStock"));
    }

    /**
     * 调用老框架定价过程
     * @param request
     * @return
     */
    public Map getPriceByGS01(SimpleRequest request){
        JSONObject jo= request.getJO();
        checkValidate(jo.getString("classifyId"),"品类编码");
        checkValidate(jo.getString("productId"),"商品编码");
        checkValidate(jo.getString("companyId"),"公司编码");
        checkValidate(jo.getString("supplierId"),"供应商编码");
        checkValidate(jo.getString("platformId"),"平台");
        checkValidate(jo.getString("uomName"),"计量单位");
        return getPriceByGS01_Inner(MapUtil.mapper("PLID",jo.getString("classifyId"),
                "SPID",jo.getString("productId"),
                "GSID",jo.getString("companyId"),
                "GYSID",jo.getString("supplierId"),
                "CGZZID",jo.getString("platformId"),
                "JLDW",jo.getString("uomName"),
                "SYGSID",jo.getString("platformId")));
    }

    public Map getPriceByGS01_Inner(Map map){
        JSONObject resultJson = piManager.synErp(
                "ipmServicePlanService.getPrice", map
        );
        return MapUtil.mapper("",resultJson.get(""));
    }

    /**
     *
     * @param id
     * @param message
     */
    private void checkValidate(String id,String message){
        if(id == null || id.trim().equals("")){
            throw new RuntimeException(message + "不能为空");
        }
    }

    public Map qryQualityInfo(SimpleRequest simpleRequest){
        JSONObject jo = simpleRequest.getJO();
//        JSONObject resultJson = piManager.synErp(
//                "ipmServicePlanService.qryQualityInfo", MapUtil.mapper("PLID",jo.getString("PLID"),"PPID",jo.getString("PPID"),"SPID",jo.getString("SPID"))
//        );
//        JSONObject reJson ;
//        try {
//            reJson = JSONObject.parseObject(resultJson.getString("obj"));
//            if(reJson == null) throw new RuntimeException("");
//        }catch (Exception e){
//            return null;
//        }
        JSONObject parm = new JSONObject();
//        parm.put("SYS_RQ", new Date());
//        parm.put("conditionStrategyId", "CX_ZBQWH");
//        parm.put("PRODUCT_ID", jo.getString("SPID")!=null?jo.getString("SPID"):"");
//        parm.put("CLASSIFY_ID", jo.getString("PLID")!=null?jo.getString("PLID"):"");
//        parm.put("BRAND_ID", jo.getString("PPID")!=null?jo.getString("PPID"):"");
//        parm.put("SUPPLIER_ID", jo.getString("GYSID")!=null?jo.getString("GYSID"):"");
//        if(!Objects.isNull(parm.get("BRAND_ID"))){
//            parm.put("",SpringManager.getBean(BrandRepository.class).findOne(parm.getString("BRAND_ID")).getQuality().getId());
//        }
        JSONObject resultJson = new ConditionBuilder.Builder("CX_ZBQWH").productId(jo.getString("SPID")).setSupplierId(jo.getString("GYSID")).build().execConditionStrategy().getResultJson();

//        Object obj = this.invoke("condition.execConditionStrategy", parm);
//        JSONObject reJson=new JSONObject(MapUtil.mapped(obj));
        return MapUtil.mapper("qualityWarranty",resultJson.getString("Z001"),"qualityMileage",resultJson.getString("Z002"));
    }

}
